import { useRouter } from 'next/router';
import { connect } from 'react-redux';
import { useState, useEffect, useCallback, useRef } from 'react';
import { message, DatePicker } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import moment from 'moment';
import emitter from '@/events';
import { getID } from '@/utils';
import { isLogin } from '@/routes_auth';
import { setDatePickerOpen } from '@/store/actions/cart';
// 抛物线
import { cartRun } from '@/plugins/cartParabola';
// css
import styles from '@/styles/CommonDetail.module.scss';
// api
import { hotelDetail } from '@/api/hotel';
import { createGoodsToCart } from '@/api/cart';
import { addCartLimit } from '../format_js';
// 组件
import Spin from '@/components/Spin';
import Item from './Order.Item';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

const OrderHotel = function ({ _setDatePickerOpen, target, projectId, algorithms, data }){

    const router = useRouter();
    const { path, date = '' } = router.query,
        id = getID(path);

    const start_date = date.split('_')[0],
        end_date = date.split('_')[1];
    
    const [more, setMore] = useState('');

    // 搜索相关
    const today = start_date ? moment(start_date) : moment().add(0, 'days'),
        tomorrow = end_date ? moment(end_date) : moment().add(1, 'days');

    const [dates, setDates] = useState([]);
    const [rangeDate, setRangeDate] = useState([today.format(dateFormat), tomorrow.format(dateFormat)]);

    const [listData, setListData] = useState(data);
    const [loading, setLoading] = useState(false);
    const [cartLoading, setCartLoading] = useState(false); // 正在加入购物车，不能再次操作

    // 监听加入购物车
    const [isOpen, setOpen] = useState(false);
    const datePicker = useRef(null);
    useEffect(() => {

        emitter.on('openDatePicker', (open) => {
            open && setOpen(true);
        });

        return function (){
            emitter.removeAllListeners(['openDatePicker']);
            _setDatePickerOpen(true);
        }
    }, []);

    // 禁用开始时间(开始时间不能大于当前时间)
    const yesterday = moment().add(-1, 'days');
    function disabledDate(current) {
        if (current <= yesterday) {
            return true
        }
        if (!dates || dates.length === 0 || (dates[0] && current > dates[0])) {
            return false
        }
        return true
    }
  
    // 选择日期
    function onCalendarChange(val) {
        setDates(val);
    }
    // 确认日期
    function onChange(val) {
        const [startDate, endDate] = [
            moment(val[0]).format(dateFormat),
            moment(val[1]).format(dateFormat)
        ];
        if(startDate == endDate){
            message.warn('入住和退房日期不能是同一天');
            return
        }
        setOpen(false);
        setLoading(true);
        setRangeDate([startDate, endDate]);
        _setDatePickerOpen(false);
        // 搜索选中日期的酒店产品
        hotelDetail({ goodsId: id, startDate, endDate }).then(res => {
            const { code, data } = res;
            if (code === 0 && data) {
                setMore('');
                setListData(data.goodsExtendListAppDTOS || []);
            } else {
                message.error('获取数据失败，请重试');
            }
            setLoading(false);
        });
    }
    // 打开picker，重置日期
    function onOpenChange(open) {
        if (open) {
            setDates([]);
            setOpen(open);
            return
        }
        setOpen(false);
    }
    
    // 去预订
    const addOrder = useCallback((data) => {
        const { goodsExtendName, specificationRefinement } = data;
        router.push({
            pathname: `${target}/${id}/${encodeURIComponent(goodsExtendName)}`,
            query: {
                sr: specificationRefinement || "",
                dn: "",
                start_date: rangeDate[0],
                end_date: rangeDate[1]
            }
        });
    }, [listData]);
    // 更改数量
    const changeNum = useCallback((value, matchId) => {
        if(value){
            listData.forEach(item => {
                if(matchId === item.id){
                    item.cartNum = value;
                }
            });
            setListData([...listData]);
        }
    }, [listData]);
    // 加入购物车
    const addCart = useCallback((event, data) => {
        const _isLogin = isLogin();
        const { asPath } = router;
        if(!_isLogin) {
            message.warn('请先登录');
            router.replace(`/login?redirect=${asPath}`);
            return
        }
        if(cartLoading){
            message.warn('请勿重复操作');
            return
        }
        const { id: goodsExtendId, salePrice, cartNum, cartNumMin, cartNumMax } = data;
        if(!cartNum){
            message.warn('请输入正确的数量');
            return
        }
        if(cartNum > cartNumMax){
            message.warn('超过最大数量，请重新输入');
            return
        }
        setCartLoading(true);
        createGoodsToCart({
            goodsId: id,
            goodsExtendId,
            projectId,
            price: salePrice,
            amount: cartNum,
            startDate: rangeDate[0],
            endDate: rangeDate[1]
        }).then(res => {
            if(res.code === 0){
                data.cartNum = cartNumMin;
                cartRun(event);
                setListData([...listData]);
            }
            setCartLoading(false);
        })
    }, [listData, cartLoading]);

    // 搜索
    const search = (
        <div className={styles['room-search']}>
            <span>入住/退房</span>
            <RangePicker
                ref={datePicker}
                open={isOpen}
                className={styles['date-picker']}
                placeholder={['入住时间', '退房时间']}
                showToday={true}
                allowClear={false}
                format={dateFormat}
                defaultValue={[today, tomorrow]}
                disabledDate={disabledDate}
                onChange={val => onChange(val)}
                onCalendarChange={val => onCalendarChange(val)}
                onOpenChange={onOpenChange}
            />
            {/* <div className={styles['room-search-btn']}>搜索</div> */}
        </div>
    )
    // 标题
    const contentTitle = (
        <div className={styles['room-list-title']}>
            <div className={styles['room-type']}>房型</div>
            <div className={styles['room-bed']}>床型</div>
            <div className={styles['room-food']}>早餐</div>
            <div className={styles['room-facility']}>政策</div>
            <div className={styles['room-price']}>房价</div>
            <div className={styles['room-stock']}>剩余</div>
        </div>
    )
    
    // 查看更多数据
    const contentMore = (
        <div className={styles['showMore']}>
            <span onClick={() => setMore(styles['showMore'])}>查看更多 <DownOutlined /></span>
        </div>
    )

    return (
        <div className={styles['hotel']}>
            <Spin loading={loading} />
            { search }
            <div className={[styles['room-list'], more].join(' ')}>
                {
                    listData.length > 5 ? contentMore : ""
                }
                { contentTitle }
                {
                    listData.map(item => {
                        const { isLimit, minNum, maxNum } = addCartLimit(item);
                        item.cartNum = item.cartNum || minNum;
                        item.cartNumMin = minNum;
                        item.cartNumMax = maxNum;
                        return <Item key={item.id} 
                                    target="/hotel"
                                    id={id}
                                    algorithms={algorithms}
                                    data={item} 
                                    isLimit={isLimit} 
                                    minNum={minNum} 
                                    maxNum={maxNum}
                                    onAddOrder={addOrder}
                                    onChangeNum={changeNum}
                                    onAddCart={addCart}
                                />
                    })
                }
            </div>
        </div >
    )
}

const mapDispatchToProps = dispatch => {
    return {
        _setDatePickerOpen: v => dispatch(setDatePickerOpen(v)),
    }
}
export default connect(null, mapDispatchToProps)(OrderHotel)